package com.lungle.warmdiary.app.view.me.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseFragment;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.event.ActiveTabHostEvent;
import com.lungle.warmdiary.app.model.response.ActiveState;
import com.lungle.warmdiary.app.model.response.CampaignState;
import com.lungle.warmdiary.app.model.response.TesterIndustry;
import com.lungle.warmdiary.app.model.response.User;
import com.lungle.warmdiary.app.utils.LevelUtil;
import com.lungle.warmdiary.app.utils.UIHelper;
import com.lungle.warmdiary.app.view.me.adapter.ActiveStateAdapter;
import com.lungle.warmdiary.app.view.me.adapter.CampaignStateAdapter;
import com.lungle.warmdiary.app.view.me.view.UserActiveView;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.util.LinkedList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 用户信息界面
 */
public class UserCenterFragment extends BaseFragment {
    private static final String USER_CENTER_SCREEN = "user center screen";

    @Bind(R.id.tv_level_exp)
    TextView levelExp;

    @Bind(R.id.campaign_gridview)
    UserActiveView campaignGridView;

    @Bind(R.id.gridview)
    UserActiveView mGridview;
    @Bind(R.id.rl_message_center)
    RelativeLayout mRlMessageCenter;
    @Bind(R.id.rl_account_center)
    RelativeLayout mRlAccountCenter;
    @Bind(R.id.rl_wallet_center)
    RelativeLayout mRlWalletCenter;
    private User mUser;
    private List<ActiveState.Item> mItems = new LinkedList<>();
    private ActiveState mActiveState = new ActiveState();
    private List<CampaignState.Item> campaignItems = new LinkedList<>();
    private CampaignState campaignState = new CampaignState();
    private ActiveStateAdapter mActiveStateAdapter;
    private CampaignStateAdapter campaignStateAdapter;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (AppContext.getInstance().isLogin()) {
            setHasOptionsMenu(true);
        } else {
            setHasOptionsMenu(false);
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(USER_CENTER_SCREEN);
        MobclickAgent.onResume(getActivity());

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(USER_CENTER_SCREEN);
        MobclickAgent.onPause(getActivity());

    }


    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_user_profile, container,
                false);
        mInflater = inflater;
        ButterKnife.bind(this, view);
        initData();
        initViews(view);

        return view;
    }

    private void initViews(View view) {
        mGridview.setAdapter(mActiveStateAdapter);
        mGridview.setOnItemClickListener((parent, view1, position, id) -> {
            ActiveState.Item item = mItems.get(position);
            EventBus.getDefault().post(new ActiveTabHostEvent(item.getState(), ActiveTabHostEvent.NORAML));
        });

        campaignGridView.setAdapter(campaignStateAdapter);
        campaignGridView.setOnItemClickListener((parent, view1, position, id) -> {
            CampaignState.Item item = campaignItems.get(position);
            EventBus.getDefault().post(new ActiveTabHostEvent(item.getState(), ActiveTabHostEvent.CAMPAING));
        });

    }


    private void fillUI() {
        if (mUser != null) {
//            if (!TextUtils.isEmpty(mUser.getUsername())) {
//                EventBus.getDefault().post(new UserChangeEvent(mUser.getUsername()));
//            }
            if (mUser.getEp() >= 0) {
                LevelUtil level = new LevelUtil(mUser.getEp());
                int levelnum = level.getLevelNum();
                String levelName = level.getLevelName();
                if (levelExp != null) {
                    if (levelnum < 9) {
                        levelExp.setText(String.format("当前级别：%s，距晋升还需经验值：%d", levelName, level.getUpgrade()));
                    } else {
                        levelExp.setText(String.format("当前级别：%s", levelName));
                    }
                }
            }
        }

    }


    @Override
    public void initData() {
        initMenu(mActiveState);
        initMenuCampaign(campaignState);
        mActiveStateAdapter = new ActiveStateAdapter(getActivity(), mItems);
        campaignStateAdapter = new CampaignStateAdapter(getActivity(), campaignItems);
        mUser = AppContext.getInstance().getLoginUser();
        loadTesterStat();
        // TODO: 16/10/4 每次都请求吗？
//        if (TextUtils.isEmpty(mUser.getUsername())) {
        ApiFactory.getUserApi().getUserProfile().subscribeOn(Schedulers.io())
                .compose(this.<Result<User>>bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<User>>(getActivity()) {
                    @Override
                    public void onNext(Result<User> userResult) {
                        super.onNext(userResult);
                        mUser = userResult.getData();
                        AppContext.getInstance().saveLoginInfo(mUser);

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);

                    }

                    @Override
                    public void onCompleted() {
                        fillUI();
                    }
                });
//        }

        getMyActiveInfo();

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.rl_message_center, R.id.rl_account_center, R.id.rl_wallet_center, R.id.rl_apply})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_message_center:
                UIHelper.showMessage(getActivity());
                break;
            case R.id.rl_account_center:
                UIHelper.showMediaCenter(getActivity());
                break;
            case R.id.rl_wallet_center:
                UIHelper.showWallet(getActivity());
                break;
            case R.id.rl_apply:
                UIHelper.showTesterStat(getActivity());


//                UIHelper.openBrowser(getActivity(), getString(R.string.actionbar_title_browser_apply), AppConstant.URL_APPLY_GUIDE);
                break;
        }
    }


    private void getMyActiveInfo() {
        ApiFactory.getUserApi().getMyActiveState().subscribeOn(Schedulers.io())
                .compose(this.<Result<ActiveState>>bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<ActiveState>>(getActivity()) {
                    @Override
                    public void onNext(Result<ActiveState> listResult) {
                        super.onNext(listResult);
                        mActiveState = listResult.getData();
                        if (mActiveState != null) mItems.clear();
                        initMenu(mActiveState);
                        mActiveStateAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        hideWaitDialog();

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideWaitDialog();
                    }
                });


        ApiFactory.getUserApi().getMyCampaignStat().subscribeOn(Schedulers.io())
                .compose(this.<Result<CampaignState>>bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<CampaignState>>(getActivity()) {
                    @Override
                    public void onNext(Result<CampaignState> listResult) {
                        super.onNext(listResult);
                        campaignState = listResult.getData();
                        if (campaignState != null) campaignItems.clear();
                        initMenuCampaign(campaignState);
                        campaignStateAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        hideWaitDialog();

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideWaitDialog();

                    }
                });

    }

    private void initMenu(ActiveState data) {
//        mItems.add(new ActiveState.Item(ActiveState.STATE_UNCONFIRM, "未确认", , data.getUnconfirm()));
        mItems.add(new ActiveState.Item(ActiveState.STATE_UNCHECK, "待审核", 0xFFFBBA5A, data.getUncheck()));
        mItems.add(new ActiveState.Item(ActiveState.STATE_UNEXECUTE, "待执行", 0xFF897172, data.getUnexecute()));
        mItems.add(new ActiveState.Item(ActiveState.STATE_PASS, "已通过", 0xFF31B909, data.getPass()
        ));
        mItems.add(new ActiveState.Item(ActiveState.STATE_UNSTART, "未开始", 0xFF6895BD, data.getUnstart()));

        mItems.add(new ActiveState.Item(ActiveState.STATE_UNPASS, "未通过", 0XFFFA4848, data.getUnpass()));
        mItems.add(new ActiveState.Item(ActiveState.STATE_REFUSE, "已拒绝", 0XFFFA4851, data.getRefuse()));
        mItems.add(new ActiveState.Item(ActiveState.STATE_ABANDON, "流单", 0XFFC86B46, data.getAbandon()));
        mItems.add(new ActiveState.Item(ActiveState.STATE_STOP, "叫停", 0XFFD1B4AD, data.getStop()));
    }

    private void initMenuCampaign(CampaignState data) {
        campaignItems.add(new CampaignState.Item(1, R.string.campaign_status_1, 0xFFFBB64D, data.getValue1()));
        campaignItems.add(new CampaignState.Item(2, R.string.campaign_status_2, 0xFFF94848, data.getValue2()));
        campaignItems.add(new CampaignState.Item(3, R.string.campaign_status_3, 0xFFF57818, data.getValue3()));
        campaignItems.add(new CampaignState.Item(4, R.string.campaign_status_4, 0xFF2DB906, data.getValue4()));
        campaignItems.add(new CampaignState.Item(5, R.string.campaign_status_5, 0xFFB5ABAA, data.getValue5()));
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.user_setting, menu);

        menu.findItem(R.id.info_setting);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        UIHelper.showUserProfile(getActivity(), mUser);
        return true;
    }

    private void loadTesterStat() {
        Observable<Result<List<TesterIndustry>>> tags;
        tags = ApiFactory.getUserApi().getTesterIndustryList();
        tags.subscribeOn(Schedulers.newThread())
                .compose(this.<Result<List<TesterIndustry>>>bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result<List<TesterIndustry>>>() {
                    @Override
                    public void onCompleted() {
                        hideWaitDialog();

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                    }

                    @Override
                    public void onNext(Result<List<TesterIndustry>> tagResult) {
                        List<TesterIndustry> mTagList = tagResult.getData();
                        AppContext.setIndustryNum(mTagList.size());
                        for (TesterIndustry industry : mTagList) {
                            AppContext.setIndustry(industry.getId(), industry.getIcon(), industry.getName());
                        }
                    }
                });


    }
}
